package com.jlgp.exam.topic250512.demo1;

import java.util.*;

/**
 * @ Description: 树的层级打印
 * @ BelongsProject: code
 * @ Author: G攀
 * @ CreateTime: 2025-05-12  00:29
 * @ Version: 1.0
 */
public class TreeLevelPrint {

    public static void print(List<Node> nodeList) {
        // 构建父节点ID到子节点列表的映射。
        Map<Integer, List<Node>> parentIdToChildren = new HashMap<>();
        for (Node node : nodeList) {
            /**
             // 检查父节点ID是否已存在于Map中
             if (!childMap.containsKey(node.parentId)) {
             // 如果不存在，创建一个新的ArrayList并关联到该父节点ID
             childMap.put(node.parentId, new ArrayList<>());
             }
             */
            parentIdToChildren.computeIfAbsent(node.parent, k -> new ArrayList<>()).add(node);
        }

        // 从根节点（parentId = 0） 开始打印
        printNodes(parentIdToChildren, 0, 0);
    }

    private static void printNodes(Map<Integer, List<Node>> parentIdToChildren, int parentId, int level) {
        /**
         获取 parentId 对应的子节点列表。如果 parentId 不存在于 Map 中，返回一个空列表（而非 null），避免后续遍历列表时出现空指针异常。
         */
        List<Node> childrens =  parentIdToChildren.getOrDefault(parentId, Collections.emptyList());
        for (Node node : childrens) {
            // 打印缩进（两个空格表示一层缩进）
            for (int i = 0; i < level; i++) {
                System.out.print("  ");
            }
            System.out.println(node.name);
            // 递归打印子节点
            printNodes(parentIdToChildren, node.id, level + 1);
        }
    }

    /**
     * 树层级打印 主方法
     */
    public static void main(String[] args) {
        List<Node> nodeList = Arrays.asList(
                new Node(1, 0, "AA"),
                new Node(2, 1, "BB"),
                new Node(3, 1, "CC"),
                new Node(4, 3, "DD"),
                new Node(4, 3, "DD"),
                new Node(5, 3, "EE"),
                new Node(6, 2, "FF"),
                new Node(7, 2, "GG"),
                new Node(8, 4, "HH"),
                new Node(9, 5, "II"),
                new Node(10, 0, "JJ"),
                new Node(11, 10, "KK"),
                new Node(12, 10, "LL"),
                new Node(13, 12, "MM"),
                new Node(14, 13, "NN"),
                new Node(15, 14, "OO")
        );
        print(nodeList);
    }
}

/**
 * 节点实体类
 */
class Node {
    // 节点id
    int id;
    // 父节点id
    int parent;
    // 节点名称
    String name;

    /**
     * 节点的构造方法
     */
    public Node(int id, int parent, String name) {
        this.id = id;
        this.parent = parent;
        this.name = name;
    }
}
